const _ = require('lodash');
const { exec } = require('child_process');
const Logger = require('../../node_core_logger');

var ffmpeg_exec = null

function zoom(req, res, next) {
  /* 处理url，保证传过来的url不管带不带zoomhelper，都只对原始url操作 */
  let liveUrl = req.query.url;
  let region = req.query.region;
  let urlHelperArr = liveUrl.split('/')
  var mediaPath = urlHelperArr[urlHelperArr.length-1].split('zoomhelper')[0];
  var publishPath = `/live/${mediaPath}`
  var session = this.sessions.get(this.publishers.get(publishPath))
  if (session) {
    var originWidth = session.videoWidth;
    var originHeight = session.videoHeight;
    var offsetWidth = 0;
    var offsetHeight = 0;
    if (region == 'leftdown') {
      offsetHeight = Math.ceil(originHeight/2)
    } else if (region == 'rightup') {
      offsetWidth = Math.ceil(originWidth/2)
    } else if (region == 'rightdown') {
      offsetWidth = Math.ceil(originWidth/2)
      offsetHeight = Math.ceil(originHeight/2)
    }
    var inPath = liveUrl.split('zoomhelper')[0];
    var outPath = inPath + 'zoomhelper'
    let execCmd = `${this.config.trans.ffmpeg} -i ${inPath} -filter:v "crop=${originWidth/2}:${originHeight/2}:${offsetWidth}:${offsetHeight}" -c:a aac -strict -2 -f flv ${outPath}`
    console.info('---------------------------------------')
    console.info(execCmd)
    console.info('---------------------------------------')
    if (ffmpeg_exec && ffmpeg_exec.stdin && !ffmpeg_exec.stdin.destroyed) { // 检查zoomhelper上是否有发布视频流
      ffmpeg_exec.stdin.write('q');
      ffmpeg_exec = null 
    }
    ffmpeg_exec = exec(execCmd);
    ffmpeg_exec.on('error', (e) => {
      Logger.ffdebug(e);
      res.json({
        errormsg: '视频流处理错误！'
      })
    });
  
    ffmpeg_exec.stdout.on('data', (data) => {
      Logger.ffdebug(`FF输出：${data}`);
    });
  
    ffmpeg_exec.stderr.on('data', (data) => {
      Logger.ffdebug(`FF输出：${data}`);
    });
    ffmpeg_exec.on('close', (code) => {
      console.log(code)
    })
    res.json({
      errormsg: ''
    })
  } else {
    res.json({
      errormsg: '当前流不可用，请稍等！'
    })
  }
}

exports.zoom = zoom;